import type { ChangeEventHandler, FC, ReactNode } from 'react'
import { memo, useEffect } from 'react'
import styles from './index.less'
import { Button, Upload, message } from 'antd'
import type { UploadProps } from 'antd'
import { UploadOutlined } from '@ant-design/icons'
import workerScript from './worker'

interface TProps {
  children?: ReactNode
}

const VideoUpload: FC<TProps> = () => {
  // useEffect(() => {
  //   const woker = new Worker(workerScript)
  //   woker.postMessage('hello world')

  //   woker.onmessage = (e) => {
  //     console.log(e.data)
  //   }
  // }, [])
  //   进一步优化上传
  const CHUNK_SIZE = 1024 * 1024 * 100 // 100MB
  //   根据硬件条件决定线程数量
  //   const WORKER_COUNT = navigator.hardwareConcurrency || 4
  const WORKER_COUNT = 4
  function cutFile(file: File) {
    return new Promise((resolve) => {
      const result: any[] = []
      const chunkCount = Math.ceil(file.size / CHUNK_SIZE)
      const workerChunkCount = Math.ceil(chunkCount / WORKER_COUNT)
      let finishCount = 0
      for (let i = 0; i < WORKER_COUNT; i++) {
        // 创建一个新的Worker 线程
        const worker = new Worker(workerScript, { type: 'module' })
        // const worker = workers()
        // 计算每个线程的开始索引和结束索引
        const startIndex = i * workerChunkCount
        let endIndex = startIndex + workerChunkCount
        if (endIndex > chunkCount) {
          endIndex = chunkCount
        }
        worker.postMessage({
          file,
          CHUNK_SIZE,
          startIndex,
          endIndex,
        })
        // eslint-disable-next-line @typescript-eslint/no-loop-func
        worker.onmessage = (e) => {
          console.log(e.data)
          for (let i = startIndex; i < endIndex; i++) {
            result[i] = e.data[i - startIndex]
          }
          worker.terminate() // 关闭线程
          finishCount++
          if (finishCount === WORKER_COUNT) {
            resolve(result)
          }
        }
      }
    })
  }
  const handleChangeFileVideo: ChangeEventHandler<HTMLInputElement> = async (e) => {
    const files = e.target.files
    if (!files?.length) return
    console.time('cutFile')
    const chunks = await cutFile(files[0])
    console.timeEnd('cutFile')
    console.log(chunks)
  }

  return (
    <div
      className={styles.VideoUpload}
      id="VideoUpload"
    >
      <h2>进一步优化</h2>
      <input
        type="file"
        onChange={handleChangeFileVideo}
      />
    </div>
  )
}

export default memo(VideoUpload)
